package com.example.mainproject;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import lib.ProcessFunc;
import lib.Consts;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import classes.CookieData;

import com.example.mainproject.R;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class LoginActivity extends Activity implements OnClickListener {

	EditText edtAccount, edtPassword;
	Button btnSign;
	String account, password;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		edtAccount = (EditText) findViewById(R.id.login_edtAccount);
		edtPassword = (EditText) findViewById(R.id.login_edtPassword);
		btnSign = (Button) findViewById(R.id.login_btnSignin);
		btnSign.setOnClickListener(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public void onClick(View v) {
		myTask myWebFetch = new myTask();
		myWebFetch.execute();
//		Log.d("test", "asdfasdfasdf");
	}

	class myTask extends AsyncTask<String, String, String> {
		InputStream is = null;

		@Override
		protected String doInBackground(String... arg0) {

			account = edtAccount.getText().toString();
			password = edtPassword.getText().toString();

			HttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(Consts.MAIN_URL);

			List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(3);
			nameValuePair.add(new BasicNameValuePair("func", "1"));
//			 nameValuePair.add(new BasicNameValuePair("uname",account));
//			 nameValuePair.add(new
//			 BasicNameValuePair("pass",ProcessFunc.getMd5Hash(password)));
			// nameValuePair.add(new BasicNameValuePair("pass",mPassword));
			nameValuePair.add(new BasicNameValuePair("uname", "duongv"));
			nameValuePair.add(new BasicNameValuePair("pass", "96e79218965eb72c92a549dd5a330112"));

			try {

				httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
				HttpResponse response = httpClient.execute(httpPost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				// String s = entity.getContent().toString();
				try {
					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is, "iso-8859-1"), 8);
					StringBuilder sb = new StringBuilder();
					String line = null;
					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}

					is.close();
					return sb.toString();
				} catch (Exception e) {
					Log.e("test", "Error converting result " + e.toString());
				}
			} catch (Exception e) {
				Log.e("test", "Error converting result " + e.toString());
			}
			return "";
		}

		@Override
		protected void onPostExecute(String result) {
//			Log.d("test", account);
//			Log.d("test", password);
			String sResponse[] = result.split("\\|");
//			for (int i = 0; i < sResponse.length; i++) {
//				Log.d("test", sResponse[i]);
//			}
			if (sResponse.length < 0) {
				ProcessFunc.ShowSimpleDialog(LoginActivity.this,
						getString(R.string.login_error_title),
						getString(R.string.login_error_message));
				return;
			}
			int ResCode = Integer.parseInt(sResponse[0]);
			if (ResCode == -1) {
				ProcessFunc.ShowSimpleDialog(LoginActivity.this,
						getString(R.string.login_error_title),
						sResponse[1].trim());
				return;
			} else {
				CookieData cookieData = new CookieData();
				cookieData.setUserId(Integer.parseInt(sResponse[1]));
				cookieData.setUserType(Integer.parseInt(sResponse[3]));
				cookieData.setIpAddress(sResponse[5]);
				cookieData.setCookie(sResponse[4]);
				
				String data = cookieData.getUserId()+"|"+cookieData.getUserType()+"|"+cookieData.getCookie()+"|"+cookieData.getIpAddress();
				try {
					ProcessFunc.WriteToFile(LoginActivity.this, Consts.F_COOKIE, data);
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
//				String appPath = getApplicationContext().getFilesDir().getAbsolutePath();
//				Log.d("test", appPath);
//				File cookie = new File(appPath, "cookie.txt");
//				if(!cookie.exists()) {
//				    try {
//
//						cookie.createNewFile();
//					} catch (IOException e) {
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//					}
//				}
//				String data = cookieData.getUserId()+"|"+cookieData.getUserType()+"|"+cookieData.getCookie()+"|"+cookieData.getIpAddress();
//				Log.d("test", data);
//	            writeData(data, appPath);
				
				Intent ticket = new Intent(getApplicationContext(),
						TicketListActivity.class);
				startActivity(ticket);
			}

			super.onPostExecute(result);
		}

	}
	
//	public void writeData(String a, String file) {
//		try {
//			FileOutputStream out = openFileOutput(file, MODE_PRIVATE);
////			OutputStreamWriter writer = new OutputStreamWriter(out);
//			Log.d("test", "ok");
//			out.write(a.getBytes());
//			Log.d("test", "done");
//			out.close();
//		} catch (FileNotFoundException e) {
//			e.printStackTrace();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//	}

}
